package com.xll.controller;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.Auth;
import com.xll.entity.*;
import com.xll.service.*;
import com.xll.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    private FoodService foodService;

    @Autowired
    private QiniuUtils qiniuUtils;

    @Autowired
    private   MedicalExaminationService medicalExaminationService;

    @Autowired
    private BloodPressureService bloodPressureService;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private KidneyService kidneyService;
    @Autowired
    private CellService cellService;


    private static final String ACCESS_KEY = "jKL84ltCx5h5kSDG3p_mIU1mZT4T_5BEcwpiN9sp";
    private static final String SECRET_KEY = "C7yf978RMp47Rig73dZFQ4JYWQPvZRFwfOH6d3o1";

    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);





    @ApiOperation(value = "通过excel批量导入")
    @PostMapping("/batchImport")
    public Result batchImport(@RequestParam("file") MultipartFile file) {
        try {
            ImportParams params = new ImportParams();
            List<Food> list = ExcelImportUtil.importExcel(file.getInputStream(), Food.class, params);
            list.forEach(item -> {
                if (StringUtils.isNotEmpty(item.getImageUrls())) {
                    try {
                        FileInputStream inputStream = new FileInputStream(item.getImageUrls());
                        String uuid = UUID.randomUUID().toString().substring(0, 7);
                        int index = item.getImageUrls().lastIndexOf(".");
                        String suffix = item.getImageUrls().substring(index);
                        String fileName = uuid + suffix;
                        String upload = qiniuUtils.upload(inputStream, fileName);
                        item.setImageUrls(upload);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            return foodService.batchImport(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("食物列表导入失败！");
        }
    }

    @ApiOperation(value = "添加菜品分类")
    @PostMapping("/type/insert")
    public Result insertType(@RequestBody FoodType foodType) {
        return foodService.insertType(foodType);
    }

    @ApiOperation(value = "删除菜品分类")
    @DeleteMapping("/type/delete/{id}")
    public Result deleteType(@PathVariable Long id) {
        return foodService.deleteType(id);
    }

    @ApiOperation(value = "修改菜品分类")
    @PostMapping("/type/update")
    public Result updateType(@RequestBody FoodType foodType) {
        return foodService.updateType(foodType);
    }
    @ApiOperation(value = "分页查询菜品分类及其菜品信息")
    @PostMapping("/type/findPage")
    public Result findPage(@RequestBody QueryInfo queryInfo) {
        return foodService.findPage(queryInfo);
    }

    @GetMapping("/typeAll")
    public Result typeAll() {
        return foodService.typeAll();
    }

    @PostMapping("/findPage")
    public Result findFoodPage(@RequestBody QueryInfo queryInfo) {
        return foodService.findFoodPage(queryInfo);
    }


    @ApiOperation(value = "小程序分页查询食物列表")
    @ApiImplicitParams({
        @ApiImplicitParam(value = "页码",name="pageNumber",required = true,dataTypeClass = Integer.class),
        @ApiImplicitParam(value = "页数大小",name="pageSize",required = true,dataTypeClass = Integer.class),
        @ApiImplicitParam(value = "食物类别",name="typeId",required = true,dataTypeClass = Long.class),
        @ApiImplicitParam(value = "关键字",name="keywords",dataTypeClass = String.class)
    })

    @PostMapping("/mini/findAll")
    public Result findMenus(@RequestBody JSONObject jsonObject) {
        return foodService.findAllByType(jsonObject);
    }

    @ApiOperation(value = "添加菜品")
    @PostMapping("/insert")
    public Result insert(@RequestBody Food food) {
        return foodService.insert(food);
    }

    @ApiOperation(value = "修改菜品")
    @PostMapping("/update")
    public Result update(@RequestBody Food food) {
        return foodService.update(food);
    }

    @ApiOperation(value = "删除菜品")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        return foodService.delete(id);
    }

    @ApiOperation(value = "根据食物类别查询食物")
    @PostMapping("/typeId")
    public Result findFoodByTypeId(@RequestBody QueryInfo queryInfo) {
        return foodService.findFoodByTypeId(queryInfo);
    }

    @GetMapping("/detail/{id}")
    public  Result  foodDetail(@PathVariable Long id){
        return  foodService.findById(id);
    }



    @PostMapping("/blood/findPage")
    public Result findAllBloodPressure(@RequestBody QueryInfo queryInfo) {
        return bloodPressureService.findPage(queryInfo);
    }

    @ApiOperation(value = "添加血压测试记录")
    @PostMapping("/insert/blood")
    public Result insertBlood(@RequestBody BloodPressure bloodPressure) {
        return bloodPressureService.insert(bloodPressure);
    }

    @ApiOperation(value = "修改血压测试记录")
    @PostMapping("/update/blood")
    public Result updateBlood(@RequestBody BloodPressure bloodPressure) {
        return bloodPressureService.update(bloodPressure);
    }

    @ApiOperation(value = "删除血压测试记录")
    @DeleteMapping("/delete/blood/{id}")
    public Result deleteBlood(@PathVariable Long id) {
        return bloodPressureService.delete(id);
    }



    @PostMapping("/MedicalExamination/findPage")
    public Result findAllMedicalExamination(@RequestBody QueryInfo queryInfo) {
        return medicalExaminationService.findPage(queryInfo);
    }

    @ApiOperation(value = "添加内科检查记录")
    @PostMapping("/insert/medicalExamination")
    public Result inserMedicalExamination(@RequestBody MedicalExamination medicalExamination) {
        return medicalExaminationService.insert(medicalExamination);
    }

    @ApiOperation(value = "修改内科检查记录")
    @PostMapping("/update/medicalExamination")
    public Result updateMedicalExamination(@RequestBody MedicalExamination medicalExamination) {
        return medicalExaminationService.update(medicalExamination);
    }

    @ApiOperation(value = "删除内科检查记录")
    @DeleteMapping("/delete/medicalExamination/{id}")
    public Result deleteMedicalExamination(@PathVariable Long id) {
        return medicalExaminationService.delete(id);
    }


    @PostMapping("/file/findPage")
    public Result findAllFile(@RequestBody QueryInfo queryInfo) {
        return sysFileService.findPage(queryInfo);
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/fileUpload")
    public Result fileUpLoad(@RequestParam("file") MultipartFile file) {
         ImportParams params = new ImportParams();
         return  Result.success("上传成功");
    }

    @ApiOperation(value = "文件存入数据库")
    @PostMapping("/file/save")
    public Result saveFile(@RequestBody List<SysFile> sysFile) {
        return sysFileService.upload(sysFile);
    }

    @ApiOperation(value = "删除文件")
    @DeleteMapping("/delete/file/{id}")
    public Result deleteFile(@PathVariable Long id) {
        return sysFileService.delete(id);
    }

    @ApiOperation(value = "修改文件名称")
    @PostMapping("/update/file")
    public Result updateFile(@RequestBody SysFile sysFile) {
        return sysFileService.update(sysFile);
    }

    public static String getDownloadUrl(String filename) throws UnsupportedEncodingException {
        //自己七牛云上的域名
        String domainOfBucket = "http://xllbyte.top";
        String encodedFileName = URLEncoder.encode(filename, "utf-8").replace("+", "%20");
        String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        return auth.privateDownloadUrl(finalUrl);
    }

    public static void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String fileUrl = getDownloadUrl(filename);
        String fileName = filename;
        //设置响应类型
        fileName = URLEncoder.encode(fileName,"UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName);
        //应用程序强制下载
        response.setContentType("application/force-download");
        //读取文件
        OutputStream out = response.getOutputStream();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(fileUrl);
        CloseableHttpResponse httpResp = httpclient.execute(httpGet);
        try{
            HttpEntity httpEntity = httpResp.getEntity();
            response.setContentLength((int) ( httpEntity).getContentLength());
            IOUtils.copy(( httpEntity).getContent(),out);
        }catch(Exception ex){
            httpclient.close();
            ex.printStackTrace();
        }finally{
            out.flush();
            out.close();
        }
    }



    @ApiOperation(value ="文件下载" )
    @RequestMapping(value = "/downLoadDailyByUrl")
    public void downLoadUrl(HttpServletRequest request, HttpServletResponse res,
                           @RequestBody SysFile sysFile) throws Exception
    {

        try{
            //文件下载
            download(sysFile.getFileName(),request,res);
        }catch (Exception e){
            e.printStackTrace();
        }



    }

    @PostMapping("/kidney/findPage")
    public Result findAllKidney(@RequestBody QueryInfo queryInfo) {
        return kidneyService.findPage(queryInfo);
    }

    @ApiOperation(value = "添加肾脏检查记录")
    @PostMapping("/insert/kidney")
    public Result insertKidney(@RequestBody Kidney kidney) {
        return kidneyService.insert(kidney);
    }

    @ApiOperation(value = "修改肾脏检查记录")
    @PostMapping("/update/kidney")
    public Result updateKidney(@RequestBody Kidney kidney) {
        return kidneyService.update(kidney);
    }

    @ApiOperation(value = "删除肾脏检查记录")
    @DeleteMapping("/delete/kidney/{id}")
    public Result deleteKidney(@PathVariable Long id) {
        return kidneyService.delete(id);
    }


    @PostMapping("/cell/findPage")
    public Result findAllCell(@RequestBody QueryInfo queryInfo) {
        return cellService.findPage(queryInfo);
    }

    @ApiOperation(value = "添加肾脏检查记录")
    @PostMapping("/insert/cell")
    public Result insertCell(@RequestBody Cell cell) {
        return cellService.insert(cell);
    }

    @ApiOperation(value = "修改肾脏检查记录")
    @PostMapping("/update/cell")
    public Result updateCell(@RequestBody Cell cell) {
        return cellService.update(cell);
    }

    @ApiOperation(value = "删除肾脏检查记录")
    @DeleteMapping("/delete/cell/{id}")
    public Result deleteCell(@PathVariable Long id) {
        return cellService.delete(id);
    }


}
